package com.xianniu.ltc.app;

import cn.devezhao.persist4j.Query;
import cn.devezhao.persist4j.engine.ID;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rebuild.core.Application;
import com.rebuild.core.BootEnvironmentPostProcessor;
import com.rebuild.core.UserContextHolder;
import com.rebuild.core.configuration.NavBuilder;
import com.rebuild.core.service.dashboard.charts.ChartData;
import com.rebuild.core.service.dashboard.charts.ChartsFactory;
import com.rebuild.utils.AppUtils;
import com.xianniu.ltc.model.entity.TXnIconConfigDTO;
import com.xianniu.ltc.model.po.ProjectQueryRelatedPO;
import com.xianniu.ltc.model.po.ProjectReportPO;
import com.xianniu.ltc.model.po.report.ChartCommonPermissionsPO;
import com.xianniu.ltc.model.vo.StatisticsXYVO;
import com.xianniu.ltc.model.vo.statistics.StatisticsYVO;
import com.xianniu.ltc.service.*;
import com.xxl.sso.core.entity.ReturnT;
import lombok.extern.slf4j.Slf4j;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author WangRuiJie
 * @Title: AppHomeController
 * @Package com.xianniu.ltc.app
 * @Description: App首页数据集
 * @date 2021/5/314:27 下午
 */
@Slf4j
@RestController
@RequestMapping(value = "/app")
public class AppHomeController{

    @Value("${H5-URL}")
    private String h5Url;

    @Autowired
    private XnIconConfigService iconConfigService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private ProjectReportService projectReportService;
    @Autowired
    private CustomizedService customizedService;
    @Autowired
    private AppHomeService appHomeService;


    @GetMapping("/homeInfo")
    public ReturnT homeInfo(HttpServletRequest request){
        final ID userId = UserContextHolder.getUser();
        // 获取租户信息
        final String tenantCode = UserContextHolder.getTenant();

        // 线索数
        Object leadCount_v = homeInfoLeadCount(userId, tenantCode);
        // 商机数(不包括赢单，输单)
        Object shangJi_v = homeInfoNicheCount(userId, tenantCode);
        // 客户数
        Object kehushu_v = homeInfoAccountCount(userId, tenantCode);
        // 合同数(不包含已作废)
        Object hetongshu_v = homeInfoContractCount(userId, tenantCode);
        // 回款计划-未收款的计划收款金额的汇总
        Object jihuashoukuanjine_v = homeInfoPlanMoneyCount(userId, tenantCode);
        // 查询赢率漏斗
        JSON yingLvJson = homeInfoWinRateCount(tenantCode);
        // 查询本年预计签约金额（未税）月
        JSON planMonthJson = homeInfoExpectMonthCount(tenantCode);
        // 查询本年预计签约金额（未税）季度
        JSON planQuarterJson = homeInfoExpectQuarterCount(tenantCode);
        // 查询本年实际签约金额（未税）月
        JSON actualMonthJson = homeInfoActualMonthCount(tenantCode);
        // 查询本年实际签约金额（未税）季度
        JSON actualQuarterJson = homeInfoActualQuarterCount(tenantCode);
        JSONObject quickFilter = new JSONObject();
        quickFilter.put("xianSuoShu", leadCount_v);
        quickFilter.put("shangJiShu", shangJi_v);
        quickFilter.put("keHuShu", kehushu_v);
        quickFilter.put("heTongShu", hetongshu_v);
        quickFilter.put("daiHuiKuanJinE", jihuashoukuanjine_v);
        quickFilter.put("yingLv", ((JSONObject) yingLvJson).get("data"));
        quickFilter.put("planMonth", planMonthJson);
        quickFilter.put("planQuarter", planQuarterJson);
        quickFilter.put("actualMonth", actualMonthJson);
        quickFilter.put("actualQuarter", actualQuarterJson);

        return new ReturnT(quickFilter);
    }

    @GetMapping("/v1/homeInfo")
//    public ReturnT v1HomeInfo(HttpServletRequest request){
//        final ID userId = UserContextHolder.getUser();
//        // 获取租户信息
//        final String tenantCode = UserContextHolder.getTenant();
//
//        // 线索数
//        Object leadCount_v = homeInfoLeadCount(userId, tenantCode);
//        // 商机数(不包括赢单，输单)
//        Object shangJi_v = homeInfoNicheCount(userId, tenantCode);
//        // 客户数
//        Object kehushu_v = homeInfoAccountCount(userId, tenantCode);
//        // 合同数(不包含已作废)
//        Object hetongshu_v = homeInfoContractCount(userId, tenantCode);
//        // 回款计划-未收款的计划收款金额的汇总
//        Object jihuashoukuanjine_v = homeInfoPlanMoneyCount(userId, tenantCode);
//        // 查询赢率漏斗
//        JSON yingLvJson = homeInfoWinRateCount(tenantCode);
//        // 地域统计 top 10
//        Object top10City = homeInfoNowYearCityTop();
//        // 客户统计 top 10
//        Object top10KeHu = homeInfoNowYearKeHuTop();
//        // 本年销售部门签约额统计
//        Object xiaoShou = homeInfoNowYearXiaoShou();
//        // 本年 周 签约额统计
//        Object actualWeek = homeInfoNowYearWeek();
//        // 本年 月 和 季 签约额统计
//        Map<String, StatisticsXYVO> actualMonthAndQuarter = homeInfoNowYearMonthAndQuarter();
//        // 历史未回款统计
//        Object historyWeiShouKuan = homeInfoHistoryWeiShouKuan();
//        // 本年 月和季 回款额统计
//        Map<String, StatisticsXYVO> huiKuanMonthAndQuarter =  homeInfoNowYearHuiKuanByMonthAndQuarter();
//        Object huiKuanWeek =  homeInfoNowYearHuiKuanByWeek();
//
//        JSONObject quickFilter = new JSONObject();
//        quickFilter.put("xianSuoShu", leadCount_v);
//        quickFilter.put("shangJiShu", shangJi_v);
//        quickFilter.put("keHuShu", kehushu_v);
//        quickFilter.put("heTongShu", hetongshu_v);
//        quickFilter.put("daiHuiKuanJinE", jihuashoukuanjine_v);
//        quickFilter.put("yingLv", ((JSONObject) yingLvJson).get("data"));
//
//        quickFilter.put("actualMonth", actualMonthAndQuarter.get("month"));
//        quickFilter.put("actualQuarter", actualMonthAndQuarter.get("quarter"));
//
//        quickFilter.put("actualWeek", actualWeek);
//        quickFilter.put("top10City", top10City);
//        quickFilter.put("top10KeHu", top10KeHu);
//        quickFilter.put("xiaoShou", xiaoShou);
//        quickFilter.put("historyWeiShouKuan", historyWeiShouKuan);
//        quickFilter.put("huiKuanMonth", huiKuanMonthAndQuarter.get("month"));
//        quickFilter.put("huiKuanQuarter", huiKuanMonthAndQuarter.get("quarter"));
//        quickFilter.put("huiKuanWeek", huiKuanWeek);
//
//        return new ReturnT(quickFilter);
//    }
    public ReturnT v1HomeInfo(HttpServletRequest request) throws Exception {
        ChartCommonPermissionsPO po = new ChartCommonPermissionsPO();
        po.setTenantCode(UserContextHolder.getTenant());
        JSONObject quickFilter = appHomeService.v1HomeInfo( po );
        return new ReturnT(quickFilter);
    }

    /**
     * 根据当前登录用户获取LTC的菜单功能权限
     *
     * @param request
     * @returnA
     */
    @GetMapping("/ltcMenu")
    @Trace
    public ReturnT ltcMenu(HttpServletRequest request) {
        // ICON不展示：销售云项目，文件，9大申请审批不在工作台直接展示
        String[] ignoreList = {"$PROJECT$", "$FILEMRG$","caigoudingdanguiji", "rbduizhangdan3"};
        // 申请审批中忽略这几个实体，这几个实体在工作台正常展示
        String[] collaborationList = {"caigoushijianguanli","jiaofushijianguanli", "shoujianfuwuqingqiu"};
        // 菜单当做公共表处理
        String tenantCode = BootEnvironmentPostProcessor.getDefaultTenant();
        // 查询有审批配置的实体
        Object[][] array = Application.createQueryNoFilter(
                "select belongEntity from RobotApprovalConfig where isDisabled = ? and tenantCode = ?")
                .setParameter(1, false)
                .setParameter(2, UserContextHolder.getTenant())
                .array();
        List<String> arrayList  = new ArrayList<>();
        if (array.length >0){
            for (Object[] o :array){
                if (!Arrays.asList(collaborationList).contains(0)){
                    arrayList.add(o[0].toString());
                }
            }
        }
        JSONArray result = new JSONArray();
        log.info("根据当前登录用户获取LTC的菜单功能权限Token:{}",UserContextHolder.getTenant());
        JSONArray navs = NavBuilder.instance.getUserNav(AppUtils.getRequestUser(request), UserContextHolder.getTenant());
        navs = (JSONArray) AppUtils.getReuqestBundle(request).replaceLangKey(navs);
        for (Object obj:navs) {
            JSONObject dataObj = JSONObject.parseObject(obj.toString());
            // 忽略动态
            if ((!Arrays.asList(ignoreList).contains(dataObj.getString("value")))
                &&(!arrayList.contains(dataObj.getString("value")))){
                if (Objects.isNull(dataObj.get("sub"))){
                    JSONObject subO = new JSONObject();
                    JSONArray subA = new JSONArray();
                    dataObj.put("icon", iconConfigService.selectIconByCode(dataObj.getString("value"), tenantCode));
                    dataObj.put("value", h5Url+dataObj.get("value"));
                    dataObj.put("flag", 1);
                    subA.add(dataObj);
                    subO.put("name", dataObj.getString("text"));
                    subO.put("value", subA);
                    result.add(subO);
                }else {
                    JSONObject subO = new JSONObject();
                    JSONArray subA = new JSONArray();
                    JSONArray subArray = dataObj.getJSONArray("sub");
                    for (Object obj1:subArray) {
                        JSONObject dataObj1 = JSONObject.parseObject(obj1.toString());
                        if ((!Arrays.asList(ignoreList).contains(dataObj1.getString("value")))
                                &&(!arrayList.contains(dataObj1.getString("value")))){
                            dataObj1.put("icon", iconConfigService.selectIconByCode(dataObj1.getString("value"), tenantCode));
                            dataObj1.put("value", h5Url+dataObj1.get("value"));
                            dataObj1.put("flag", 1);
                            subA.add(dataObj1);
                        }
                    }
                    if(!subA.isEmpty()){
                        subO.put("name", dataObj.getString("text"));
                        subO.put("value", subA);
                        result.add(subO);
                    }
                }
            }
        }

        JSONObject subApprovalO = new JSONObject();
        JSONArray subApprovalA = new JSONArray();
        // 增加申请审批特殊层级
        JSONObject approvaJ = new JSONObject();
        approvaJ.put("flag", 2);
        approvaJ.put("icon", iconConfigService.selectIconByCode("approval", tenantCode));
        approvaJ.put("text", "申请审批");
        approvaJ.put("type", 21);
        approvaJ.put("value", "");
        subApprovalA.add(approvaJ);
        //临时与H5联调"我的审批"，暂时放在销售菜单级别
        JSONObject approval = new JSONObject();
        approval.put("flag", 1);
        approval.put("icon", iconConfigService.selectIconByCode("$FEEDS$", tenantCode));
        approval.put("text", "我的审批");
        approval.put("type", "ENTITY");
        approval.put("value", h5Url + "approvalList");
        subApprovalA.add(approval);
        subApprovalO.put("name", "审批");
        subApprovalO.put("value", subApprovalA);
        result.add(subApprovalO);
        return new ReturnT(result);
    }

    /**
     * 项目：查询当前人在某个模块中拥有的实体权限集合
     * @param param
     * @return
     */
    @PostMapping("/selectEntityCodeList")
    public ReturnT selectEntityCodeList(@RequestBody ProjectQueryRelatedPO param, HttpServletRequest request){
        log.info("查询当前人在某个模块中拥有的实体权限集合:{}", JSON.toJSON(param));
        UserContextHolder.setTenant(param.getTenantCode());
        JSONArray navs = NavBuilder.instance.getUserNav(AppUtils.getRequestUser(request), param.getTenantCode());
        navs = (JSONArray) AppUtils.getReuqestBundle(request).replaceLangKey(navs);
        return projectService.selectEntityCodeList(param, navs);
    }

    /**
     * 项目：查询当前人在某个模块中拥有的实体权限集合
     * @param param
     * @return
     */
    @PostMapping("/selectApprovalList")
    public ReturnT selectApprovalList(@RequestBody ProjectQueryRelatedPO param, HttpServletRequest request){
        UserContextHolder.setTenant(param.getTenantCode());
        JSONArray navs = NavBuilder.instance.getUserNav(AppUtils.getRequestUser(request), param.getTenantCode());
        navs = (JSONArray) AppUtils.getReuqestBundle(request).replaceLangKey(navs);
        return projectService.selectApprovalList(param, navs);
    }

    /**
     * 项目：查询报表数据
     * @param
     * @return
     */
    @PostMapping("/getProjectReport")
    public ReturnT getProjectReport(@RequestBody ProjectReportPO reportPO){
        log.info("项目报表统计参数：#{}",reportPO);
        return projectReportService.getProjectReport(reportPO);

    }

    /**
     * 获取本月开始日期
     * @return String
     * **/
    public String getMonthStart(){
        Calendar cal=Calendar.getInstance();
        cal.add(Calendar.MONTH, 0);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        Date time=cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd ").format(time)+" 00:00:00";
    }

    /**
     * 获取今天
     * @return String
     * */
    public String getToday(){
        return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
    }

    /**
     * 获取本月开始日期
     * @return String
     * **/
    public Date getMonthStartDate(){
        Calendar cal=Calendar.getInstance();
        cal.add(Calendar.MONTH, 0);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        Date time=cal.getTime();
        return time;
    }

    /**
     * APP首页-查询私海所属线索数
     * @param userId
     * @param tenantCode
     * @return
     */
    public Object homeInfoLeadCount(ID userId, String tenantCode){

        String sql0 = String.format("select count(owningUser) from sihaixiansuo where tenantCode = ? and owningUser = ?");
        Query leadCount = Application.createQueryNoFilter(sql0)
                .setParameter(1, tenantCode)
                .setParameter(2, userId);
        Object[] result0 = leadCount.unique();
        Object leadCount_v = Objects.isNull(result0[0]) ? 0:result0[0];
        return leadCount_v;
    }

    /**
     * APP首页-查询商机数
     * @param userId
     * @param tenantCode
     * @return
     */
    public Object homeInfoNicheCount(ID userId, String tenantCode){
        String sql = String.format("select count(owningUser) from rbshangji4 where tenantCode = ? and owningUser = ? and shangjijieduanyinglv not in ('019-017a613777930008','019-017a61371dfc0007')");
        Query shangJiShu = Application.createQueryNoFilter(sql)
                .setParameter(1, tenantCode)
                .setParameter(2, userId);
        Object[] result1 = shangJiShu.unique();
        Object shangJi_v = Objects.isNull(result1[0]) ? 0:result1[0];
        return shangJi_v;
    }

    /**
     * APP首页-查询客户数
     * @param userId
     * @param tenantCode
     * @return
     */
    public Object homeInfoAccountCount(ID userId, String tenantCode){
        String sql = String.format("select count(owningUser) from sihaikehu where tenantCode = ? and owningUser = ?");
        Query kehushu = Application.createQueryNoFilter(sql)
                .setParameter(1, tenantCode)
                .setParameter(2, userId);
        Object[] result2 = kehushu.unique();
        Object kehushu_v = Objects.isNull(result2[0]) ? 0:result2[0];
        return kehushu_v;
    }

    /**
     * APP首页-查询合同数
     * @param userId
     * @param tenantCode
     * @return
     */
    public Object homeInfoContractCount(ID userId, String tenantCode){
        String sql = String.format("select count(owningUser) from rbhetong0 where tenantCode = ? and owningUser = ? and hetongjieduan <> '019-0179930e6def01fa'");
        Query hetongshu = Application.createQueryNoFilter(sql)
                .setParameter(1, tenantCode)
                .setParameter(2, userId);
        Object[] result3 = hetongshu.unique();
        Object hetongshu_v = Objects.isNull(result3[0]) ? 0:result3[0];
        return hetongshu_v;
    }

    /**
     * APP首页-计划收款金额
     * @param userId
     * @param tenantCode
     * @return
     */
    public Object homeInfoPlanMoneyCount(ID userId, String tenantCode){
        String sql = String.format("select sum(jihuashoukuanjine) from huikuanjihua where tenantCode = ? and owningUser = ? and huikuanzhuangtai  = '012-01760df25cf30039'");
        Query jihuashoukuanjine = Application.createQueryNoFilter(sql)
                .setParameter(1, tenantCode)
                .setParameter(2, userId);
        Object[] result4 = jihuashoukuanjine.unique();
        Object jihuashoukuanjine_v = Objects.isNull(result4[0]) ? 0:new BigDecimal(result4[0].toString()).setScale(2,BigDecimal.ROUND_HALF_UP);
        return jihuashoukuanjine_v;
    }

    /**
     * APP首页-计划收款金额
     * @param tenantCode
     * @return
     */
    public JSON homeInfoWinRateCount(String tenantCode){
        String chartId = "017-017767c92a570cf0";
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("id", chartId);
        JSON yingLvJson = null;
        try{
            ChartData chart = ChartsFactory.create(ID.valueOf(chartId), tenantCode);
            yingLvJson = chart.setExtraParams(paramMap).build(tenantCode);
        }catch (Exception e){
            e.printStackTrace();
            log.info("没有商机权限:{}",e.getMessage());
            JSONObject jso = new JSONObject();
            jso.put("data", new String[0]);
            yingLvJson = jso;
        }
        log.info("输出赢率漏斗：{}", yingLvJson);
        return yingLvJson;
    }

    /**
     * APP首页-本年预计签约金额（未税）月
     * @param tenantCode
     * @return
     */
    public JSON homeInfoExpectMonthCount(String tenantCode){
        String chartId1 = "017-017c172e2d17038d";
        Map<String, Object> paramMap1 = new HashMap<>();
        paramMap1.put("id", chartId1);
        ChartData chart1 = null;
        JSON planMonthJson = null;
        try{
            chart1 = ChartsFactory.create(ID.valueOf(chartId1), tenantCode);
            planMonthJson = chart1.setExtraParams(paramMap1).build(tenantCode);
        }catch (Exception e){
            log.info(e.getMessage());
            List<String> dimAxis = new ArrayList<>();
            JSONArray yyyAxis = new JSONArray();
            JSONObject order = new JSONObject();
            order.put("xAxis", JSON.toJSON(dimAxis));
            order.put("yyyAxis", JSON.toJSON(yyyAxis));
            planMonthJson = order;
        }

        log.info("输出本年预计签约金额（未税）月：{}", planMonthJson);
        return planMonthJson;
    }

    /**
     * APP首页-本年预计签约金额（未税）季度
     * @param tenantCode
     * @return
     */
    public JSON homeInfoExpectQuarterCount(String tenantCode){
        String chartId2 = "017-017c17303ee7038e";
        Map<String, Object> paramMap2 = new HashMap<>();
        paramMap2.put("id", chartId2);
        ChartData chart2 = null;
        JSON planQuarterJson = null;
        try{
            chart2 = ChartsFactory.create(ID.valueOf(chartId2), tenantCode);
            planQuarterJson = chart2.setExtraParams(paramMap2).build(tenantCode);
        }catch (Exception e){
            log.info(e.getMessage());
            List<String> dimAxis = new ArrayList<>();
            JSONArray yyyAxis = new JSONArray();
            JSONObject order = new JSONObject();
            order.put("xAxis", JSON.toJSON(dimAxis));
            order.put("yyyAxis", JSON.toJSON(yyyAxis));
            planQuarterJson = order;
        }
        log.info("本年预计签约金额（未税）季度：{}", planQuarterJson);
        return planQuarterJson;
    }

    /**
     * APP首页-本年实际签约金额（未税）月
     * @param tenantCode
     * @return
     */
    public JSON homeInfoActualMonthCount(String tenantCode){
        String chartId3 = "017-017c173222a4038f";
        Map<String, Object> paramMap3 = new HashMap<>();
        paramMap3.put("id", chartId3);
        ChartData chart3 = null;
        JSON actualMonthJson = null;
        try {
            chart3 = ChartsFactory.create(ID.valueOf(chartId3), tenantCode);
            actualMonthJson = chart3.setExtraParams(paramMap3).build(tenantCode);
        }catch (Exception e){
            log.info(e.getMessage());
            List<String> dimAxis = new ArrayList<>();
            JSONArray yyyAxis = new JSONArray();
            JSONObject order = new JSONObject();
            order.put("xAxis", JSON.toJSON(dimAxis));
            order.put("yyyAxis", JSON.toJSON(yyyAxis));
            actualMonthJson = order;
        }
        log.info("输出本年实际签约金额（未税）月：{}", actualMonthJson);
        return actualMonthJson;
    }

    /**
     * APP首页-本年实际签约金额（未税）季度
     * @param tenantCode
     * @return
     */
    public JSON homeInfoActualQuarterCount(String tenantCode){
        String chartId4 = "017-017c1733f0da0393";
        Map<String, Object> paramMap4 = new HashMap<>();
        paramMap4.put("id", chartId4);
        ChartData chart4 = null;
        JSON actualQuarterJson = null;
        try {
            chart4 = ChartsFactory.create(ID.valueOf(chartId4), tenantCode);
            actualQuarterJson = chart4.setExtraParams(paramMap4).build(tenantCode);
        }catch (Exception e){
            log.info(e.getMessage());
            List<String> dimAxis = new ArrayList<>();
            JSONArray yyyAxis = new JSONArray();
            JSONObject order = new JSONObject();
            order.put("xAxis", JSON.toJSON(dimAxis));
            order.put("yyyAxis", JSON.toJSON(yyyAxis));
            actualQuarterJson = order;
        }
        log.info("本年实际签约金额（未税）季度：{}", JSON.toJSON(actualQuarterJson));
        return actualQuarterJson;
    }

    /**
     * 地域统计 top
     * @return
     */
    public Object homeInfoNowYearCityTop()
    {
        try {
            log.info("进入top10===1 地域");
            ChartCommonPermissionsPO po = new ChartCommonPermissionsPO();
            po.setTenantCode(UserContextHolder.getTenant());
            return customizedService.queryNowYearCityTop(po);
        }catch (Exception e){
            log.info(e.getMessage());
            StatisticsXYVO xyVo = new StatisticsXYVO();
            return xyVo;
        }
    }

    /**
     * 客户统计 top
     * @return
     */
    public Object homeInfoNowYearKeHuTop()
    {
        try {
            log.info("进入top10===2 客户");
            ChartCommonPermissionsPO po = new ChartCommonPermissionsPO();
            po.setTenantCode(UserContextHolder.getTenant());
            return customizedService.queryNowYearKeHuTop( po );
        }catch (Exception e){
            log.info(e.getMessage());
            StatisticsXYVO xyVo = new StatisticsXYVO();
            return xyVo;
        }
    }

    /**`
     * 销售统计
     * @return
     */
    public Object homeInfoNowYearXiaoShou()
    {
        try {
            log.info("进入===3 销售部门");
            ChartCommonPermissionsPO po = new ChartCommonPermissionsPO();
            po.setTenantCode(UserContextHolder.getTenant());
            return customizedService.queryNowYearXiaoShouBuMen( po );
        }catch (Exception e){
            log.info(e.getMessage());
            StatisticsXYVO xyVo = new StatisticsXYVO();
            return xyVo;
        }
    }

    /**`
     * 本年-周-统计
     * @return
     */
    public Object homeInfoNowYearWeek()
    {
        try {
            log.info("进入===4 本年签约额统计 周");
            ChartCommonPermissionsPO po = new ChartCommonPermissionsPO();
            po.setTenantCode(UserContextHolder.getTenant());
            return customizedService.queryNowYearWeek( po );
        }catch (Exception e){
            log.info(e.getMessage());
            StatisticsXYVO xyVo = new StatisticsXYVO();
            return xyVo;
        }
    }

    /**`
     * 历史未收款统计 90天以内 , 90-180天 , 180天以上
     * @return
     */
    public Object homeInfoHistoryWeiShouKuan()
    {

        try {
            log.info("进入===5 历史累计应收未收款统计");
            ChartCommonPermissionsPO po = new ChartCommonPermissionsPO();
            po.setTenantCode(UserContextHolder.getTenant());
            return customizedService.queryHistoryWeiShouKuan( po );
        }catch (Exception e) {
            log.info(e.getMessage());
            StatisticsXYVO historyWeiShouKuan = new StatisticsXYVO();
            return historyWeiShouKuan;
        }
    }

    /**
     * 本年回款统计-月+季度
     * @return
     */
    public Map<String, StatisticsXYVO> homeInfoNowYearHuiKuanByMonthAndQuarter()
    {
        try {
            log.info("进入===6 本年回款统计 月");
            ChartCommonPermissionsPO po = new ChartCommonPermissionsPO();
            po.setTenantCode(UserContextHolder.getTenant());
            Map<String, StatisticsXYVO> huiKuanMonthAndQuarter = customizedService.selectMonthCashTransferSchemesData( po );
            log.info("本年回款统计-月 和 季=== {}", JSON.toJSON(huiKuanMonthAndQuarter));
            return huiKuanMonthAndQuarter;
        }catch (Exception e){
            log.info(e.getMessage());

            // 月度
            List<String> yMonthData = new ArrayList<String>();
            // 设置Y轴数据
            StatisticsYVO monthYVo = new StatisticsYVO();
            monthYVo.setData( yMonthData );
            monthYVo.setName( "本年回款统计" );
            // 周统计数据
            StatisticsXYVO huiKuanMonth = new StatisticsXYVO();
            List xMonthData = new ArrayList();
            huiKuanMonth.setXAxis(xMonthData);
            huiKuanMonth.setYyyAxis(monthYVo);

            // 季度
            List<String> yQuarterData = new ArrayList<String>();
            // 设置Y轴数据
            StatisticsYVO quarterYVo = new StatisticsYVO();
            quarterYVo.setData( yQuarterData );
            quarterYVo.setName( "本年回款统计" );
            // 周统计数据
            StatisticsXYVO huiKuanQuarter = new StatisticsXYVO();
            List xQuarterData = new ArrayList();
            huiKuanQuarter.setXAxis(xQuarterData);
            huiKuanQuarter.setYyyAxis(quarterYVo);


            Map<String, StatisticsXYVO> huiKuanMonthAndQuarter = new HashMap<String, StatisticsXYVO>();
            huiKuanMonthAndQuarter.put("month", huiKuanMonth );
            huiKuanMonthAndQuarter.put("quarter", huiKuanQuarter );

            return huiKuanMonthAndQuarter;
        }
    }

    /**
     * 本年回款统计-周
     * @return
     */
    public Object homeInfoNowYearHuiKuanByWeek()
    {
        try {
            // TODO
            ChartCommonPermissionsPO po = new ChartCommonPermissionsPO();
            po.setTenantCode(UserContextHolder.getTenant());
            StatisticsXYVO huiKuanWeek = customizedService.selectWeekCashTransferSchemesData( po );
            log.info("本年回款统计-周=== {}", JSON.toJSON(huiKuanWeek));
            return huiKuanWeek;
        }catch (Exception e){
            log.info(e.getMessage());
            List<String> yWeekData = new ArrayList<String>();
            // 设置Y轴数据
            StatisticsYVO weekYVo = new StatisticsYVO();
            weekYVo.setData( yWeekData );
            weekYVo.setName( "本年回款统计" );
            // 周统计数据
            StatisticsXYVO huiKuanWeek = new StatisticsXYVO();
            List xWeekData = new ArrayList();
            huiKuanWeek.setXAxis(xWeekData);
            huiKuanWeek.setYyyAxis(weekYVo);
            return huiKuanWeek;
        }
    }

    /**
     * 本年签约额统计-月+季度
     * @return
     */
    public Map<String, StatisticsXYVO> homeInfoNowYearMonthAndQuarter()
    {
        try {
            log.info("进入===8 本年签约额统计 月和季");
            ChartCommonPermissionsPO po = new ChartCommonPermissionsPO();
            po.setTenantCode(UserContextHolder.getTenant());
            Map<String, StatisticsXYVO> actualMonthAndQuarter = customizedService.queryNowYearMonthAndQuarter( po );
            log.info("本年签约额统计-月 和 季=== {}", JSON.toJSON(actualMonthAndQuarter));
            return actualMonthAndQuarter;
        }catch (Exception e){
            log.info(e.getMessage());

            // 月度
            List<String> yMonthData = new ArrayList<String>();
            // 设置Y轴数据
            StatisticsYVO monthYVo = new StatisticsYVO();
            monthYVo.setData( yMonthData );
            monthYVo.setName( "本年签约额统计" );
            // 周统计数据
            StatisticsXYVO huiKuanMonth = new StatisticsXYVO();
            List xMonthData = new ArrayList();
            huiKuanMonth.setXAxis(xMonthData);
            huiKuanMonth.setYyyAxis(monthYVo);

            // 季度
            List<String> yQuarterData = new ArrayList<String>();
            // 设置Y轴数据
            StatisticsYVO quarterYVo = new StatisticsYVO();
            quarterYVo.setData( yQuarterData );
            quarterYVo.setName( "本年签约额统计" );
            // 周统计数据
            StatisticsXYVO huiKuanQuarter = new StatisticsXYVO();
            List xQuarterData = new ArrayList();
            huiKuanQuarter.setXAxis(xQuarterData);
            huiKuanQuarter.setYyyAxis(quarterYVo);


            Map<String, StatisticsXYVO> actualMonthAndQuarter = new HashMap<String, StatisticsXYVO>();
            actualMonthAndQuarter.put("month", huiKuanMonth );
            actualMonthAndQuarter.put("quarter", huiKuanQuarter );

            return actualMonthAndQuarter;
        }
    }
}
